from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import Session, sessionmaker

from app.core.config import settings

# 配置异步引擎的连接池参数，防止连接泄漏或长时间 Sleep 导致的池阻塞
async_engine = create_async_engine(
  settings.mysql_async_url,
  echo=settings.debug,
  future=True,
  pool_size=10,
  max_overflow=20,
  pool_recycle=1800,  # 30 分钟回收，避免 MySQL 空闲断开
  pool_pre_ping=True,  # 每次借出前探活，清理失效连接
  pool_timeout=30,
)
async_session_factory = async_sessionmaker(async_engine, expire_on_commit=False)

sync_engine = None
SessionLocal: sessionmaker[Session] | None = None


async def get_async_session() -> AsyncSession:
  async with async_session_factory() as session:
    try:
      yield session
    finally:
      await session.close()
